/**
 * \file Auth_Login_Fragment.java
 * \author Nicolaj Quottrup
 */
package com.rootbat.fleamarketapp.authorization;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.google.gson.reflect.TypeToken;
import com.rootbat.fleamarketapp.android.R;
import com.rootbat.fleamarketapp.utilities.JsonResult;
import com.rootbat.fleamarketapp.utilities.IHttpToolkit.EHTTP_TYPE;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
* \brief Fragment class to show login screen
*/
public class Auth_Login_Fragment extends Fragment {
	// Holder for activity on attach
	private IServerFragmentFunctions authFunc;

    /// <summary>
    /// onCreateView - Sets up fragment view and adds button listeners.
    /// </summary>
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// Setup View
		View view = inflater.inflate(R.layout.fragment_auth_login, container, false);
		
		// Add click listeners
		Button loginButton = (Button) view.findViewById(R.id.auth_login_button_login);
		loginButton.setOnClickListener(LoginClickListener);
		
		Button registerButton = (Button) view.findViewById(R.id.auth_login_button_register);
		registerButton.setOnClickListener(RegisterClickListener);
		
		Button cancelButton = (Button) view.findViewById(R.id.auth_login_button_cancel);
		cancelButton.setOnClickListener(CancelClickListener);
		
		return view;
	}
	
    /// <summary>
    /// ClickLogin - Click on login button, starts login request on service to call server with provided values.
    /// </summary>
	public void ClickLogin() {
		// Get user input data fields
		EditText email = (EditText)getActivity().findViewById(R.id.auth_login_edittext_email);
		EditText password = (EditText)getActivity().findViewById(R.id.auth_login_edittext_password);
		
		// Add user input data text to list for POST data to server.
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("email", email.getText().toString()));
		list.add(new BasicNameValuePair("password", password.getText().toString()));
		
		// Start new thread and request login with values.
		authFunc.getServerService().Request(getActivity(), "Auth_Login", getActivity().getString(R.string.root_url), "authorization", "Login", EHTTP_TYPE.HTTP_POST, list, new TypeToken<JsonResult<Object>>(){}.getType());
	}
	
    /// <summary>
    /// ClickCancel - Click on cancel button, closes authorization module activity
    /// </summary>
	public void ClickCancel() {
		getActivity().finish();
	}
	
    /// <summary>
    /// ClickRegister - Click on register button, shifts fragment in authorization module to register fragment
    /// </summary>
	public void ClickRegister() {
		Auth_Register_Fragment regFragment = new Auth_Register_Fragment();
		FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.auth_fragment_container, regFragment);
		transaction.commit();
	}
	
    /// <summary>
    /// onAttach - Sets title of activity to name of fragment, registers receiver to receive calls from serverservice, and get activity instance
    /// </summary>
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof IServerFragmentFunctions) {
			authFunc = (IServerFragmentFunctions) activity;
		} 
		else {
		      throw new ClassCastException(activity.toString() + " must implemenet FragmentActivityFunctions");
		}
		
		getActivity().setTitle(R.string.auth_login);
		IntentFilter intentFilter = new IntentFilter(ServerService.RECEIVER);
		getActivity().registerReceiver(bReceiver, intentFilter);
	}
	
    /// <summary>
    /// onDetach - remove activity instance and unregister serverservice receiver
    /// </summary>
	@Override
	public void onDetach() {
		super.onDetach();
		authFunc = null;
		getActivity().unregisterReceiver(bReceiver);
	}
	
    /// <summary>
    /// bReceiver - Internal broadcastreceiver to handle fragment specific serverservice broadcasts. 
    /// </summary>
	BroadcastReceiver bReceiver = new BroadcastReceiver() {
	    /// <summary>
	    /// onReceive - Receive function for broadcasts
	    /// </summary>
        @Override
        public void onReceive(Context context, Intent intent) {
        	// Get activity bound service
        	ServerService serv = authFunc.getServerService();
        	// If request sent is Auth_login, respond to call.
        	if(intent.getStringExtra("Action").equals("Auth_Login"))
        	{
        		// Get serverservice respond result
        		JsonResult<Object> resa = serv.getResult("Auth_Login");
        		// If there was response
        		if(resa != null)
        		{	
        			// If its successfull close login module, else notify user of failure
        			if(resa.Success == 1)
        			{
	        			EditText email = (EditText)getActivity().findViewById(R.id.auth_login_edittext_email);
	        			EditText password = (EditText)getActivity().findViewById(R.id.auth_login_edittext_password);
        			
        				Global.getInstance().Email = email.getText().toString();
        				Global.getInstance().Password = password.getText().toString();
        				getActivity().finish();
        			}
        			else
        			{
        				Toast.makeText(getActivity(), getString(R.string.auth_fail_login), Toast.LENGTH_SHORT).show();
        			}
        		}
        	}
        }
    };
	
    /// <summary>
    /// LoginClickListener - Definition of LoginClickListener
    /// </summary>
	final OnClickListener LoginClickListener = new OnClickListener() {
	    /// <summary>
	    /// onClick - Calls ClickLogin when login button is clicked.
	    /// </summary>
		@Override
	    public void onClick(View v) {
			ClickLogin();
	    }
	};
	
    /// <summary>
    /// CancelClickListener - Definition of CancelClickListener
    /// </summary>
	final OnClickListener CancelClickListener = new OnClickListener() {
	    /// <summary>
	    /// onClick - Calls ClickCancel when cancel button is clicked.
	    /// </summary>
		@Override
	    public void onClick(View v) {
			ClickCancel();
	    }
	};
	
    /// <summary>
    /// RegisterClickListener - Definition of RegisterClickListener
    /// </summary>
	final OnClickListener RegisterClickListener = new OnClickListener() {
	    /// <summary>
	    /// onClick - Calls ClickRegister when register button is clicked.
	    /// </summary>
		@Override
	    public void onClick(View v) {
			ClickRegister();
	    }
	};
}

